<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Profile extends Public_Controller
{
	public function __construct()
	{
		parent::__construct();
		$userData = $this->session->all_userData();
		if (!isset($userData['logged_in']) || !$userData['logged_in']){
			redirect('./');
		}
		$this->load->model('uploking_users_m');
		$this->load->library(array('keywords/keywords'));
		$this->load->library('form_validation');
		$this->lang->load('uploking');
		$this->load->helper('uploking');
		$this->validation_rules = array(
			array(
				'field' => 'first_name',
				'label' => 'lang:uploking_home_first_name_label',
				'rules' => 'trim|required|max_length[255]'
			),
			array(
				'field' => 'last_name',
				'label' => 'lang:uploking_home_last_name_label',
				'rules' => 'trim|required|max_length[255]'
			),
			array(
				'field' => 'username',
				'label' => 'lang:uploking_home_username_label',
				'rules' => 'trim|required|max_length[255]|min_length[6]'
			),
			array(
				'field' => 'email',
				'label' => 'lang:uploking_home_email_label',
				'rules' => 'trim|required|max_length[255]'
			),
			array(
				'field' => 'password',
				'label' => 'lang:uploking_home_password_label',
				'rules' => 'trim|max_length[255]|min_length[6]|matches[retype_password]'
			),
			array(
				'field' => 'retype_password',
				'label' => 'lang:uploking_home_retype_password_label',
				'rules' => 'trim|max_length[255]'
			),
		);
	}

	// blog/page/x also routes here
	public function index()
	{
		$userData = $this->session->all_userData();
		$user = $this->uploking_users_m->get($userData['account']['user_id']);
		$this->form_validation->set_rules($this->validation_rules);
		if ($this->form_validation->run()){
			$password = $this->input->post('password');
			if($password){
				$password = md5($password);
			}else{
				$password = $user->password;
			}
			$user->first_name = $this->input->post('first_name');
			$user->last_name = $this->input->post('last_name');
			
			$this->uploking_users_m->update( $user->id, array(
				'first_name'	=> $this->input->post('first_name'),
				'last_name'	=> $this->input->post('last_name'),
				'password'	=> $password
			));
		}		
		$this->template
		->title($this->module_details['name'])
		->set('user', $user)
		->build('profile', $this->data);
	}
}
